package com.durian.base.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import androidx.annotation.RequiresPermission;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.durian.BaseApp;
import com.durian.base.frame.BaseDurianConfig;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 说明：AndroidInfoUtils
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019-06-14 18:47
 * <p/>
 * 版本：version 1.0
 */
public class AndroidInfoUtils {

    private AndroidInfoUtils() {
    }

    private static TelephonyManager getTelephonyManager() {
        return (TelephonyManager) BaseApp.getApp().getSystemService(Context.TELEPHONY_SERVICE);
    }

    /**
     * 说明：获取手机IMEI号码(Android10无法获取)
     *
     * @return 返回手机IMEI号码
     */
    @SuppressLint("HardwareIds")
    @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
    @Deprecated
    public static String getImeiCode() {
        TelephonyManager tm = getTelephonyManager();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P){
            return "";
        }if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return tm.getImei();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                Class clazz = tm.getClass();
                //noinspection unchecked
                Method getImeiMethod = clazz.getDeclaredMethod("getImei");
                getImeiMethod.setAccessible(true);
                String imei = (String) getImeiMethod.invoke(tm);
                if (imei != null) return imei;
            } catch (Exception e) {
                Log.e("AndroidInfoUtils", "getIMEI: ", e);
            }
        }
        String imei = tm.getDeviceId();
        if (imei != null && imei.length() == 15) {
            return imei;
        }
        return "";
    }

    /**
     * 获取手机Android_ID
     *
     * @return MacAddress String
     */
    public static String getAndroidId() {
        String id = SPUtils.get(BaseDurianConfig.FILE_NAME_ANDROID_ID).enableEncrypt(false).readString(BaseDurianConfig.KEY_ANDROID_ID);
        if (StringUtils.isNotEmpty(id)){
            return id;
        }
        String androidId = Settings.Secure.getString(BaseApp.getApp().getContentResolver(),
                                                     Settings.Secure.ANDROID_ID);
        if (StringUtils.isEmpty(androidId)){
            androidId = UUID.randomUUID().toString();
        }
        SPUtils.get(BaseDurianConfig.FILE_NAME_ANDROID_ID).enableEncrypt(false).write(BaseDurianConfig.KEY_ANDROID_ID,androidId);
        return androidId;
    }

    /**
     * 检查包名是否存在
     *
     * @param packageName
     * @return
     */
    public static boolean checkPackage(String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = BaseApp.getApp().getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    /**
     * 说明：获取系统信息
     *
     * @return
     */
    public static String getOs() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 说明：获取应用名称
     * @return
     */
    public static String appName(){
        try {
            PackageManager packageManager = BaseApp.getApp().getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    BaseApp.getApp().getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return BaseApp.getApp().getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 说明：获取当前应用程序的VersionName
     * <p>
     * 当前上下文环境
     *
     * @return 返回当前应用的版本号
     */
    public static String versionName() {
        try {
            PackageInfo info = BaseApp.getApp().getPackageManager().getPackageInfo(
                    BaseApp.getApp().getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 说明：获取当前应用程序的VersionCode
     *
     * @return 返回当前应用的版本号
     */
    public static int versionCode() {
        try {
            PackageInfo info = BaseApp.getApp().getPackageManager().getPackageInfo(
                    BaseApp.getApp().getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 说明：检测手机空间可用大小 get the space is left over on phone self
     */
    public static long getRealSizeOnPhone() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        @SuppressWarnings("deprecation")
        long blockSize = stat.getBlockSize();
        @SuppressWarnings("deprecation")
        long availableBlocks = stat.getAvailableBlocks();
        long realSize = blockSize * availableBlocks;
        return realSize;
    }

    /**
     * 说明：获取设备终端码
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getTerminalCode() {
        String terminalCode = SPUtils.get(BaseDurianConfig.FILE_NAME).readString(BaseDurianConfig.KEY_TERMINAL_CODE);
        if (StringUtils.isNotEmpty(terminalCode)){
            return terminalCode;
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P){
            String androidId = getAndroidId();
            if (TextUtils.isEmpty(androidId)){
                terminalCode = MD5.getMD5(UUID.randomUUID().toString());
            }else {
                terminalCode = MD5.getMD5(androidId);
            }
        }else {
            try {
                terminalCode = MD5.getMD5(getImeiCode() + getAndroidId());
            } catch (Exception e) {
                terminalCode = MD5.getMD5(UUID.randomUUID().toString());
            }
        }
        SPUtils.get(BaseDurianConfig.FILE_NAME).write(BaseDurianConfig.KEY_TERMINAL_CODE,terminalCode);
        return terminalCode;

    }

    /**
     * 获取手机系统SDK版本
     *
     * @return 如API 17 则返回 17
     */
    public static int getSDKVersion() {
        return Build.VERSION.SDK_INT;
    }

    /**
     * 获取设备的可用内存大小
     *
     * @return 当前内存大小
     */
    public static int getDeviceUsableMemory() {
        ActivityManager am = (ActivityManager) BaseApp.getApp()
                .getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        // 返回当前系统的可用内存
        return (int) (mi.availMem / (1024 * 1024));
    }

    /**
     * 小米手机
     *
     * @return
     */
    public static boolean isXiaoMi() {
        return StringUtils.isEqualsIgnoreCase(android.os.Build.BRAND, "xiaomi");
    }

    /**
     * 魅族手机
     *
     * @return
     */
    public static boolean isMeiZu() {
        return StringUtils.isEqualsIgnoreCase(android.os.Build.BRAND, "meizu");
    }

    /**
     * 获取MateData数据
     * @param key
     * @param defValue
     * @return
     */
    public static String metaData(String key,String defValue) {
        String result = defValue;
        try {
            ApplicationInfo appInfo;
            appInfo = BaseApp.getApp().getPackageManager().getApplicationInfo(BaseApp.getApp().getPackageName(),
                                                                                        PackageManager.GET_META_DATA);
            if (appInfo != null && appInfo.metaData.containsKey(key)){
                result = appInfo.metaData.getString(key,defValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判断服务是否开启
     *
     * @return
     */
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (("").equals(ServiceName) || ServiceName == null)
            return false;
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(200);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(ServiceName)) {
                return true;
            }
        }
        return false;

    }
}
